package org.arpit.masteringextjs.dao.impl;

import java.util.List;

import org.arpit.masteringextjs.dao.ActorDAO;
import org.arpit.masteringextjs.dao.DBUtility;
import org.arpit.masteringextjs.domain.Actor;
import org.arpit.masteringextjs.domain.User;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;

public class ActorDAOImpl implements ActorDAO{

	private static ActorDAO actorDAO;
	private SessionFactory sessionFactory = DBUtility.getSessionFactory();
	private ActorDAOImpl () {
		
	}
	
	public static ActorDAO getInstance() {
		if(actorDAO == null) {
			actorDAO = new ActorDAOImpl();
		}
		return actorDAO;
	}
	
	@Override
	public List<Actor> findAll() {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Actor.class);
		crit.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
		List<Actor> actors = crit.list();
		session.getTransaction().commit();
		session.close();
		return actors;
	}

	@Override
	public Actor create(Actor actor) {
		if(actor.getId() != null){
			throw new IllegalArgumentException("Invalid id for creation : " + actor.getId());
		}
		
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Actor createdActor = (Actor) session.merge(actor);
		session.getTransaction().commit();
		session.close();
		return createdActor;
	}

	@Override
	public Actor update(Actor actor) {
		if(actor.getId() == null || actor.getId() == 0) {
			throw new IllegalArgumentException("Invalid data");
		}
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Actor updatedActor = (Actor) session.merge(actor);
		session.getTransaction().commit();
		session.close();
		return updatedActor;
	}

	@Override
	public void delete(long id) {
		Session session = sessionFactory.openSession();
		session.beginTransaction();
		Criteria crit = session.createCriteria(Actor.class);
		crit.add(Restrictions.eq("id", id));
		List<Actor> actors = crit.list();
		if(actors.isEmpty()) {
			throw new IllegalArgumentException("Actor with id " + id +" not found");
		}
		Actor actor = actors.get(0);
		session.delete(actor);
		session.getTransaction().commit();
		session.close();
	}

}
